<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="流动申请信息编号" prop="applyCode">
        <el-input
          v-model="queryParams.applyCode"
          placeholder="请输入流动申请信息编号"
          style="width: 240px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="流动人口ID" prop="populationId">
        <el-input
          v-model="queryParams.populationId"
          placeholder="请输入流动人口ID"
          style="width: 240px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['flow:flowApply:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['flow:flowApply:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['flow:flowApply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['flow:flowApply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="flowApplyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="applyId" />-->
      <el-table-column label="序号" align="center" width="50" type="index" />
      <el-table-column label="流动申请信息编号" width="250" align="center" prop="applyCode" >
        <template #default="scope">
          <el-link type="primary" @click="getFlowApplyDetail(scope.row)" v-hasPermi="['population:hukou:list']">
            {{ scope.row.applyCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="流动人口姓名" align="center" width="150" prop="populationId" >
        <template #default="scope">
          {{ (populationList.find(item => item.populationId === scope.row.populationId) || {}).populationName || '未指定' }}
        </template>
      </el-table-column>
      <el-table-column label="流动起始日期" align="center" prop="applyStartTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流动结束日期" align="center" prop="applyEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="applyStatus">
        <template #default="scope">
          <dict-tag :options="flow_apply_status" :value="scope.row.applyStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="流程类型" align="center" width="250px" prop="processDefinitionKey">
        <template #default="scope">
          <dict-tag :options="process_definition_key" :value="scope.row.processDefinitionKey"/>
        </template>
      </el-table-column>
      <el-table-column label="当前审批人" align="center" width="200px" prop="approveBy" />
      <el-table-column label="流程实例id" align="center" prop="processInstanceId" width="300px" />
      <el-table-column label="操作" align="center" width="200px"
                       fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['flow:flowApply:edit']">修改</el-button>-->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['flow:flowApply:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改流动申请对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="flowApplyRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="流动人口姓名" prop="populationName" v-if="!form.applyId">
          <el-input v-model="form.populationName" placeholder="选择人员信息后系统将会自动填充流动人口的相关信息" disabled readonly>
            <template #append>
              <el-button type="info" icon="Search" @click="choosePopulation"/>
            </template>
          </el-input>
        </el-form-item>
        <!-- 隐藏的输入框用于存储ID -->
        <el-form-item prop="populationId" style="display: none;">
          <el-input v-model="form.populationId"></el-input>
        </el-form-item>

        <el-form-item label="流动起始日期" prop="applyStartTime">
          <el-date-picker clearable
                          v-model="form.applyStartTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择流动起始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="流动结束日期" prop="applyEndTime">
          <el-date-picker clearable
                          v-model="form.applyEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择流动结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="流程类型" prop="processDefinitionKey">
          <el-select v-model="form.processDefinitionKey" placeholder="请选择流程类型">
            <el-option
                v-for="dict in process_definition_key"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="申请原因" prop="applyReason">
          <el-input v-model="form.applyReason" placeholder="请输入申请原因" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="流动申请信息详情" v-model="flowApplyDetailOpen" width="800px" append-to-body>
      <template #header="{ close, titleId, titleClass }">
        <div style="display: flex; align-items: center;">
          <h4 :id="titleId" :class="titleClass" style="flex-grow: 1;">流动申请信息详情</h4>
          <el-dropdown placement="bottom-start"
                       trigger="click"
                       @command="(command) => approval(form.applyId, command)"
                       style="margin-right: 20px">
            <el-button type="warning"
                       :disabled="!(form.approveBy === name)"
                       v-hasPermi="['flow:flowApply:edit']">
              <el-icon class="el-icon--left"><EditPen /></el-icon>
              审批
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="0">同意</el-dropdown-item>
                <el-dropdown-item command="1">驳回</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
      <el-descriptions border :column="1">
        <el-descriptions-item label="流动申请信息编号">{{form.applyCode}}</el-descriptions-item>
        <el-descriptions-item label="流动人口姓名">
          {{ (populationList.find(item => item.populationId === form.populationId) || {}).populationName || '未指定' }}
        </el-descriptions-item>
        <el-descriptions-item label="流动起始日期">
          {{ form.applyStartTime }}
        </el-descriptions-item>
        <el-descriptions-item label="流动结束日期">
          {{ form.applyEndTime }}
        </el-descriptions-item>
        <el-descriptions-item label="申请原因">{{ form.applyReason }}</el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <dict-tag :options="flow_apply_status" :value="form.applyStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="当前审批人">{{ form.approveBy }}</el-descriptions-item>
        <el-descriptions-item label="流程实例id">{{ form.processInstanceId }}</el-descriptions-item>
        <el-descriptions-item label="流程类型">
          <dict-tag :options="process_definition_key" :value="form.processDefinitionKey"/>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ form.createBy }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ form.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="修改人">{{ form.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="备注" v-if="form.remark && form.remark.trim() !== ''" width="100">
          <el-input v-model="form.remark" type="textarea" :readOnly="true" disabled />
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 选择流动人口表单-->
    <el-dialog
        title="选择流动人口"
        v-model="isChoosePopulationDialogVisible"
        width="80%"
    >

      <div class="app-container">
        <!-- 查询表单 -->
        <el-form :model="queryPopulationParams" ref="queryPopulationRef" :inline="true" v-show="showSearch">
          <el-form-item label="流动人口编码" prop="populationCode">
            <el-input
                v-model="queryPopulationParams.populationCode"
                placeholder="请输入流动人口编码"
                style="width: 240px"
                clearable
                @keyup.enter="handlePopulationQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handlePopulationQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetPopulationQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row>
          <!-- 表格数据展示 -->
          <el-table v-loading="loading" :data="populationList"
                    highlight-current-row
                    @current-change="handleCurrentChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" width="50" type="index" />
            <el-table-column label="流动人口编号" align="center" width="250" prop="populationCode" />
            <el-table-column label="姓名" align="center" prop="populationName" />
            <el-table-column label="年龄" align="center" prop="populationAge" />
            <el-table-column label="照片" align="center" prop="populationImage" width="100">
              <template #default="scope">
                <image-preview :src="scope.row.populationImage" :width="50" :height="50"/>
              </template>
            </el-table-column>
            <el-table-column label="现居住地" align="center" prop="populationAddress" />
            <el-table-column label="手机号" align="center" prop="populationPhone" />
          </el-table>

          <pagination
              v-show="populationTotal>0"
              :total="populationTotal"
              v-model:page="queryPopulationParams.pageNum"
              v-model:limit="queryPopulationParams.pageSize"
              @pagination="getPopulationList"
          />
        </el-row>

      </div>

    </el-dialog>
  </div>
</template>

<script setup name="FlowApply">
import {
  listFlowApply,
  getFlowApply,
  delFlowApply,
  addFlowApply,
  updateFlowApply,
  flowApplyApproval
} from "@/api/flow/flowApply";
import {listPopulation} from "@/api/population/population.js";
import useUserStore from "@/store/modules/user.js";

const { proxy } = getCurrentInstance();
const { flow_apply_status, process_definition_key } = proxy.useDict('flow_apply_status', 'process_definition_key');

const flowApplyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyCode: null,
    populationId: null,
  },
  // 人员查询表单
  queryPopulationParams: {
    pageNum: 1,
    pageSize: 10,
    populationCode: null
  },
  rules: {
    populationName: [
      { required: true, message: "流动申请姓名不能为空", trigger: "change" }
    ],
    applyStartTime: [
      { required: true, message: "流动起始日期不能为空", trigger: "change" }
    ],
    applyEndTime: [
      { required: true, message: "流动结束日期不能为空", trigger: "change" }
    ],
    processDefinitionKey: [
      { required: true, message: "流程类型不能为空", trigger: "change" }
    ],
    applyReason: [
      { required: true, message: "申请原因不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, queryPopulationParams, form, rules } = toRefs(data);

// 自定义
// 当前登录用户的账号
const name = useUserStore().name;
const flowApplyDetailOpen = ref(false);
const populationList = ref([])
// 选择人员弹窗
const isChoosePopulationDialogVisible = ref(false);
// 选择人员弹窗数据总数
const populationTotal = ref(0);


/** 查询流动申请列表 */
function getList() {
  loading.value = true;
  listFlowApply(queryParams.value).then(response => {
    flowApplyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    applyId: null,
    applyCode: null,
    populationId: null,
    applyStartTime: null,
    applyEndTime: null,
    applyReason: null,
    applyStatus: null,
    approveBy: null,
    processInstanceId: null,
    processDefinitionKey: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    delFlag: null
  };
  proxy.resetForm("flowApplyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.applyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加流动申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _applyId = row.applyId || ids.value
  getFlowApply(_applyId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改流动申请";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["flowApplyRef"].validate(valid => {
    if (valid) {
      if (form.value.applyId != null) {
        updateFlowApply(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFlowApply(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _applyIds = row.applyId || ids.value;
  proxy.$modal.confirm('是否确认删除流动申请编号为"' + _applyIds + '"的数据项？').then(function() {
    return delFlowApply(_applyIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('flow/flowApply/export', {
    ...queryParams.value
  }, `flowApply_${new Date().getTime()}.xlsx`)
}

getList();

// 自定义区域
// 获取流动申请详情
function getFlowApplyDetail(row) {
  reset();
  const _id = row.applyId;
  getFlowApply(_id).then(response => {
    form.value = response.data;
    flowApplyDetailOpen.value = true;
  })
}

// 查询流动人口信息
function getPopulationList() {
  loading.value = true;
  listPopulation(queryPopulationParams.value).then(response => {
    populationList.value = response.rows;
    populationTotal.value = response.total;
    loading.value = false;
  })
}
getPopulationList();

/** 重置按钮操作 */
function resetPopulationQuery() {
  proxy.resetForm("queryPopulationRef");
  handlePopulationQuery();
}
// 选择按钮
function choosePopulation() {
  resetPopulationQuery()
  // 打开选择弹窗（不需要请求后端，这里只是为了回显）
  isChoosePopulationDialogVisible.value = true;
}
// 搜索
function handlePopulationQuery() {
  queryPopulationParams.value.pageNum = 1;
  getPopulationList();
}
// 确认选中
function handleCurrentChange(currentRow) {
  console.log(currentRow);
  if (!currentRow) return; // 如果没有选中任何行，直接返回
  proxy.$modal.confirm(`是否确认选中流动人员${currentRow.populationName}`)
      .then(() => {
        // 用户确认选择
        form.value.populationId = currentRow.populationId;
        form.value.populationName = currentRow.populationName;
        proxy.$modal.msgSuccess("选中成功");
        // 关闭选择对话框
        isChoosePopulationDialogVisible.value = false;
      })
      .catch(() => {
        // 用户取消选择
        proxy.$modal.msgWarning("取消选中");
      });
}

// 审批按钮
function approval(applyId, command) {
  // 组装参数
  const data = {
    applyId: applyId,
    approvalStatus: command
  }
  flowApplyApproval(data).then(response => {
    proxy.$modal.msgSuccess("审批成功");
    flowApplyDetailOpen.value = false;
    getList();
  })
}
</script>
